package com.project.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Calendar;
import java.util.Map;
import java.util.Set;

public class JWTUtil {
    private static final String SING = "!lovoyny";

    /**
     * 创建token
     * @param map
     * @return
     */
    public static String getToken(Map<String,Object> map){
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, 30);

        JWTCreator.Builder b = JWT.create();
       Set<String> keySet = map.keySet();
        try {
            ObjectMapper om = new ObjectMapper();
            for (String key : keySet) {
                String str = om.writeValueAsString(map.get(key));
                b.withClaim(key, str);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return b.withExpiresAt(c.getTime()).sign(Algorithm.HMAC256(SING));
    }


    /**
     * 验证合法性，并返回DecodedJWT
     * @param token
     */
    public static Object getTokenInfo(String token,String name,Class objClass){
        DecodedJWT dj = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        String str = dj.getClaim(name).asString();
        try {
            Object  s = new ObjectMapper().readValue(str,objClass);
            return s;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
